# coding:utf-8
# https://www.cnblogs.com/zhiyiYo/p/15676079.html
import os
import sys
import time

import resources.resource_rc
from PyQt5.QtCore import QRect, QRectF, QSize, Qt, QCoreApplication, pyqtSignal, QPoint, QDir, QTimer, QEvent
from PyQt5.QtGui import QPainter, QPixmap, QWheelEvent, QKeySequence, QPen, QBrush, QTransform, QFont, QTouchEvent
from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsPixmapItem,
                             QGraphicsScene, QGraphicsView, QShortcut, QFileDialog, QGraphicsRectItem,
                             QGraphicsLineItem, QGraphicsSimpleTextItem)

from utils.pictureHandlers import PicturesReader


class OthersTestWindow(QGraphicsView):
    """ 图片查看器 """
    toTestDetailSignal = pyqtSignal(dict)  # 主界面的信号用来绑定子界面类的函数方法

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('GraphicsViewWindow get config Version', self.myConfig.version)

        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 测试记录
        # self.testDetailWin = TestDetailWindow()
        # self.toTestDetailSignal.connect(self.testDetailWin.RecvMainData)
        # for item in self.picturesReader.file_paths:
        #     emitData = {'status': False, "item": item, "remarks": '', 'type': 0, }
        #     self.toTestDetailSignal.emit(emitData)
        # self.testDetailWin.show()
        # 初始化小部件
        self.__initWidget()

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def __initWidget(self):
        """ 初始化小部件 """
        self.resize(800, 600)
        # 隐藏滚动条
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # 以鼠标所在位置为锚点进行缩放
        self.setTransformationAnchor(self.AnchorUnderMouse)

        # 平滑缩放
        # self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.setRenderHints(QPainter.Antialiasing |
                            QPainter.SmoothPixmapTransform)

        # 设置场景
        # self.graphicsScene.addItem(self.pixmapItem)
        # 创建场景
        self.graphicsScene = QGraphicsScene()
        self.graphicsScene.clearSelection()  # 【清除选择】
        self.setScene(self.graphicsScene)
        self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.setSceneRect(0, 0, 800, 600)  # fix scene size 500 500
        self.setRenderHint(QPainter.Antialiasing)  ##设置视图的抗锯齿渲染模式。

        # 通过图标
        self.pixmapRi = QPixmap(':/icons/icons/right.png')
        self.pixmapItemRi = QGraphicsPixmapItem(self.pixmapRi)
        self.pixmapItemRi.setScale(0.1)
        self.pixmapItemRi.setPos(self.width() / 2, self.height() / 2)
        self.pixmapItemRi.setVisible(False)
        self.graphicsScene.addItem(self.pixmapItemRi)
        self.timeoutTimer = QTimer()
        self.timeoutTimer.timeout.connect(self.TimeoutFun)

        # 提示文字
        tipText = QGraphicsSimpleTextItem('全屏与退出全屏：\n               F11')
        tipText.setPen(QPen(Qt.gray))
        tipText.setPos(self.myConfig.screenLength / 8, self.myConfig.screenWidth / 2)
        tipText.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable)
        # tipText.setScale(1.5)
        tipText.setFont(QFont(self.font().family(), 20))
        self.graphicsScene.addItem(tipText)
        # 画对脚线
        # line1 = QGraphicsLineItem(0, 0, self.myConfig.screenLength, self.myConfig.screenWidth)
        # line1.setPen(QPen(Qt.gray))
        # line2 = QGraphicsLineItem(0, self.myConfig.screenWidth, self.myConfig.screenLength, 0)
        # line2.setPen(QPen(Qt.gray))
        # rect.setBrush(QBrush(Qt.blue))
        # 加入场景
        # self.graphicsScene.addItem(line1)
        # self.graphicsScene.addItem(line2)

    # def DrawRectFun(self, rectX=0, rectY=0):
    def TimeoutFun(self):
        self.pixmapItemRi.setVisible(False)
        self.timeoutTimer.stop()

    # def mouseDoubleClickEvent(self, event):
    #     # point = self.mapToScene(event.pos())
    #     # item = self.graphicsScene.itemAt(point, QTransform())
    #     # self.graphicsScene.removeItem(item)
    #     self.WindowSizeFun()
    #     super().mouseDoubleClickEvent(event)

    def viewportEvent(self, event: QEvent):  # real signature unknown; restored from __doc__
        """ viewportEvent(self, QEvent) -> bool """
        QGraphicsView.viewportEvent(self, event)
        print('~' * 30)
        type = event.type()
        pointPosList = []
        print('QEvent.type', type)
        try:
            pt = event.pos()  # 获取鼠标坐标--view坐标
            print('view坐标:{},{}'.format(pt.x(), pt.y()))
            # 添加一个圆环
            cycle = self.graphicsScene.addEllipse(0, 0, 60, 60)
            cycle.setPen(QPen(Qt.yellow))
            cycle.setPos(pt.x(), pt.y())
        except Exception as e:
            print('Error:', e)
        if type == QEvent.TouchBegin or type == QEvent.TouchEnd or type == QEvent.TouchUpdate:
            pointPosList.clear()
            touchEvent = QTouchEvent(event)
            # print('touchEvent',touchEvent)
            touchPoints = touchEvent.touchPoints()
            # print('touchPoints type', type(touchPoints)) 不可type
            # // 这里处理下，一般来说第一个点会被处理自动转换为鼠标
            # // 所以你需要添加一个bool的标识来在mouse事件处理时候
            # // 判断要不要处理
            for touchPoint in touchPoints:
                print('touchPoint.pos', touchPoint.pos())
                if touchPoint.id() == 0:
                    if touchPoint.state() == Qt.TouchPointPressed:
                        mouseTouchInProgress = True
                    elif touchPoint.state() == Qt.TouchPointReleased:
                        mouseTouchInProgress = False
                #  处理touch其实更多是对点状态的处理
                touchState = touchPoint.state()
                print('touchPoint.state()', touchState)
                if touchState == Qt.TouchPointPressed:
                    pass
                elif touchState == Qt.TouchPointMoved:
                    pass
                elif touchState == Qt.TouchPointReleased:
                    pass
                try:
                    pt = touchPoint.pos()  # 获取鼠标坐标--view坐标
                    print('view坐标:{},{}'.format(pt.x(), pt.y()))
                    # 添加一个圆环
                    cycle = self.graphicsScene.addEllipse(0, 0, 60, 60)
                    cycle.setPen(QPen(Qt.red))
                    cycle.setPos(pt.x(), pt.y())
                except Exception as e:
                    print('Error:', e)
        # // 触摸结束
        if type == QEvent.TouchEnd:
            pass
        print('~' * 30)
        return False

    # def mouseMoveEvent(self, evt):
    #     pt = evt.pos()  # 获取鼠标坐标--view坐标
    #     QGraphicsView.mouseMoveEvent(self, evt)
    # print('view坐标:{},{}'.format(pt.x(), pt.y()))
    def get_item_at_click(self, e):
        pos = e.pos()
        item = self.itemAt(pos)
        return item


if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    w = OthersTestWindow()
    # 首先设置接收触控事件
    w.setAttribute(Qt.WA_AcceptTouchEvents, True)
    w.show()
    # w.showFullScreen()
    sys.exit(app.exec_())
